import {
	Component
} from 'react';
import {
	Tab,
	Button,
	ScrollList,
	ActionSheet,
	Group,
	Boxs,
	Avatar,
	Badge,
	Popup,
	Dialog,
	Toast,
	SearchBar
} from 'saltui';
const {
	IconButton
} = Button;
const {
	HBox,
	Box,
	VBox
} = Boxs;

import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap
} from '../../../app/variables';
import DB from '../../../app/db';
let ActionSheetButton;
let pageNum = 1;
let pageSize = 10;
let commentAll = "";
let commentListAll = [];
class Item extends Component {
	constructor(props) {
		super(props);
		var context = document.getElementById("context").value;
		this.state = {
			option: [],
			commentList:[],
			id:this.props.postId,
		}

		this.OPERATE = [
			{
				name: '回复',
				code: 'comment'
			},
			{
				name: '删除',
				code: 'delete'
			}
		];
		
	}
	componentWillMount() {
		this.getCommentList();
	}

	componentWillUnmount(){
		if(ActionSheetButton){
	      ActionSheetButton.close();
	    }
	}

	getCommentList(){
		commentAll = "";
		commentListAll = [];
		pageNum = 1;
		var param = {
			page:pageNum,
			id:this.state.id,
			pageSize:pageSize
		};
		DB.ForumModuleAPI.queryPostPageComment(param).then((content) => {
			commentListAll = content.data;
				this.setState({
					commentList:content.data
				})
				}).catch((error) => {
					Toast.show({
						type: 'error',
						content: error.errorMsg,
				});
			});
	}

	getCommentListNext(){
		pageNum = pageNum + 1;
		var page = pageNum;
		var param = {
			page:page,
			id:this.state.id,
			pageSize:pageSize
		};
		DB.ForumModuleAPI.queryPostPageComment(param).then((content) => {
			var list = content.data;
			for(var i=0;i<list.length;i++){
			      commentListAll.push(list[i]);
			}
				this.setState({
					commentList:commentListAll
				})
				}).catch((error) => {
					Toast.show({
						type: 'error',
						content: error.errorMsg,
				});
			});
	}

	judgeOperate(isAuthor,isModerator,mainPostIsAuthor) {
		let option = this.generateIndependentOptions();
		if(this.props.boardStatus == '1' && this.props.boardIsDelete =='0')
		this.pushInIndependentOptions(option, 'comment');
		if(isAuthor||isModerator||mainPostIsAuthor){
			this.pushInIndependentOptions(option, 'delete');
		}
		this.setState({
			option: option
		});
	}
	generateIndependentOptions() {
		return new Array();
	}

	pushInIndependentOptions(options, code) {
		if (options instanceof Array) {
			let n = this.acquireOptionWithName(code);
			options.push(n);
		}
		return options;
	}

	acquireOptionWithName(n) {
		let s;
		this.OPERATE.map((item, index) => {
			if (item.code == n) {
				s = item;
				return item;
			}
		});
		return s;
	}

	acquireIndependentOptionsName(options) {
		let names = [];
		if (options && options.length > 0) {
			options.map((item, index) => {
				names.push(item.name);
			});
		}
		return names;
	}

	handleOperateClick(isAuthor,isModerator,id,authorName,boardId,nowAuthor,receiverId,postId,handleOperateClick) {
	 	let t = this;
	 	this.judgeOperate(isAuthor,isModerator,handleOperateClick);
		if( t.state.option.length == 0){
			return;
		}
		if((t.state.option.length == 1 && t.state.option[0].name== '删除')|| t.state.option.length == 2){
			ActionSheetButton = ActionSheet.show({
				options: t.acquireIndependentOptionsName(t.state.option),
				destructiveButtonIndex: t.state.option.length-1,
				maskClosable: true,
			}, t.clickOperateItem.bind(t, t.state.option,id,authorName,boardId,nowAuthor,receiverId,postId));
		}else{
			ActionSheetButton = ActionSheet.show({
				options: t.acquireIndependentOptionsName(t.state.option),
				maskClosable: true,
			}, t.clickOperateItem.bind(t, t.state.option,id,authorName,boardId,nowAuthor,receiverId,postId));
		}
	}

	clickOperateItem(option,id,authorName,boardId,nowAuthor, receiverId,postId,index) {
		if (index == -1) {
			return;
		}
		let opt = option[index];
		 if (opt.code == 'delete') {
		 	this.showConfirm('delete', '确定要删除吗？', {
				id: id
			});
		}
		if (opt.code == 'comment') {
			var placeholderComment = "回复@"+authorName+"...";
			location.hash = 'post/reply/' + '0' + '/' + postId + '/' + boardId + '/undefined/undefined/' + nowAuthor + '/' + '4'+'/'+ placeholderComment +'/' + '4/' + receiverId;
	   }
	}

	showConfirm(optionCode, content, param) {
		Dialog.confirm({
			 title: '提示',
			content: content,
			onConfirm: this.confirmDialogButton.bind(this, optionCode, param),
			onCancel: (var1) => {
				console.log('confirm cancel');
			},
		});
	}

	confirmDialogButton(optionCode, argParam) {
		let t = this;
		if (optionCode == 'delete') {
			let param = {
				ids: argParam.id
			};
			DB.ForumModuleAPI.deletePost(param).then((content) => {
				Toast.show({
					type: 'success',
					content: '删除成功',
				});
				this.getCommentList();	
				}).catch((error) => {
					Toast.show({
						type: 'error',
						content: error.errorMsg,
				});
			});
		}
	}

	render() {
		var url=this.props.urlPrev;
		var imgUrl = '';
		if (this.state.commentList && this.state.commentList.length > 0) {
			commentAll = this.state.commentList.map((item, index) => {
				if(item.image != null&&item.image != ''){
					imgUrl = url + item.image+'&token='+this.props.token;
				}
				return (
					<div className="dd-bottom-border t-MB14">
						<Box className=" t-ML14 t-WH40 t-FL  ">
							{
								(imgUrl!=null&&imgUrl!='')?<Avatar src={imgUrl} size={40} />: <Avatar name={item.authorName}  size={40} style={{ fontSize:12}}/>
							}
						</Box>
						<VBox  onClick={this.handleOperateClick.bind(this,item.isAuthor,item.isModerator,item.id,item.authorName,item.board_id,item.nowAuthor,item.id,item.postId,item.mainPostIsAuthor)}>
			               	<VBox className="t-MT2">
			                	<Box className="t-MT2 t-ML10 t-MB8">{item.authorName}{item.receiverName}</Box>
			                	<Box className="t-ML10 t-MB10 t-FCddfontblue-40 t-FS12">{item.createdDate}</Box>
			              	</VBox>
			              	<Box className="t-MT5 t-MB16 t-ML10 t-LH1_4 t-omit2" style={{ width: "94%" }} dangerouslySetInnerHTML={{__html: item.content}}></Box>
		            	</VBox>
						<div className="t-CL"></div>
					</div>
				);
			});
		}
		return (
			<div>
				<HBox className="dd-bottom-border t-MB12">
				    <Box className="t-MT14 t-ML16  t-MB14">全部回复({this.state.commentList.length})</Box>
			    </HBox>
				{commentAll}
				{
					this.state.commentList && this.state.commentList.length == 10 ?
					<Box className="t-MT10 t-ML14 t-FCddblue t-MB10" style={{textAlign:"center"}} onClick={this.getCommentListNext.bind(this)}>加载更多<i className="iconfont icon-arrow-down t-FCddblue"></i></Box>
					:
					""
				}
	     	</div>
			
		);
	}
}


export default class PageHome extends Component {

	constructor(props) {
		super(props);
		var hasBottomTab =  document.getElementById("hasBottomTab").value;
		let id = props.params.id;
		let num = props.params.num;
		let authorFloor = props.params.author;
		let authorNameRe = props.params.authorName;
		let createdDate = props.params.createdDate;
		let boardIsDelete = props.params.boardIsDelete;
		let boardStatus = props.params.boardStatus;
		let image = props.params.image;
		let isAnonymity = props.params.isAnonymity;
		let url = props.params.url
		let winHeight = hasBottomTab == 1 ? getScrollHigh(0, 1, 1) : getScrollHigh(0, 1, 0);
		var context = document.getElementById("context").value;
		this.state = {
			boardIsDelete:boardIsDelete,
			boardStatus:boardStatus,
			winHeight: winHeight,
			id:id,
			authorFloor:authorFloor,
			num:num,
			authorNameRe:authorNameRe,
			content:"",
			createdDate:createdDate,
			image:image,
			attIdJson:[],
			isAnonymity:isAnonymity,
			url:url,
			urlPrev: context + '/api/m/plugin/attachment/mobile/viewImage?fid=',
		}

		dd.biz.navigation.setTitle({
      		title: "查看回复",
		    onSuccess: function (result) {
		    },
     		 onFail: function () {
      		}
    		});

}

	componentWillMount() {
		this.getPhoto();
	}
	componentDidMount() {
		window.scrollTo(0,0);
	}


	getPhoto(){
		let param = {
			id: this.state.id,
		};
		DB.ForumModuleAPI.viewReplyPost(param).then((content) => {
			this.setState({
				attIdJson: content.attIdJson,
				content:content.contentPost
			})
			
		}).catch((error) => {
			errorCallBack();
		});
	}

	beforeFetch(data, from) {
		data.rows = data.pageSize;
		data.limit = data.pageSize;
		data.id=this.state.id;
		return data;
	}

	processData(data) {
		return data;
	}

	flushViewData(){
		var param = {};
		this.refs.post_comment_ref.fetchData(param);
	}

	render() {
		let photo_html='';
		var url=this.state.urlPrev;
		var token = document.getElementById("token").value;
		if (this.state.attIdJson && this.state.attIdJson.length > 0) {
			photo_html = this.state.attIdJson.map((item, index) => {
				var imageContent=url+item.id+'&token='+token;
				return (
					<Box flex={1} className="t-OFH t-P2" style={{width:"100%",height:"200"}}>
                      <img className="t-R4" src={imageContent} style={{ width: "100%", height: "100%" }}  />
                    </Box>
				);
			});
		}
		
		
		let replyUserName = this.state.authorNameRe.split('<');
		var createdDate = '';
		if(this.state.createdDate != undefined&&this.state.createdDate!='undefined'){
			createdDate = this.state.createdDate.substr(5,11);
		}
		var imgUrl = '';
		if(this.state.image != null && this.state.image != '' && this.state.image != 'null' && this.state.image != 'undefined' && this.state.image != undefined){
			imgUrl = url + this.state.image+'&token='+token;
		}
		let winHeightStyle = {
			height:this.state.winHeight
		};
		return (
		<div>
			<div className=" t-PT16 t-PL16 t-PR16  dd-bottom-border t-BCf t-PB6">
				<HBox>
					<Box className="t-list-img t-WH40">
						{
		          			(imgUrl!=null&&imgUrl!='')?<Avatar src={imgUrl} size={40} />: <Box  className="t-list-img t-WH30"> <Avatar name={replyUserName[0]}  size={40} style={{ fontSize:12}}/> </Box>
		         		}
				  	</Box>
				  	<VBox flex={1}>
						<HBox className="t-FBJ">
					  		<HBox className="t-list-title t-PR10" flex={1}>
								<Box className="t-omit t-PR6 t-PT1 t-FS14" >{this.state.authorNameRe}</Box>
					  		</HBox>
					  		{
			                  	this.state.num == '1'?
			                  	<Box className="dd-t-list-time t-FCddfontblue-60"><span>沙发</span></Box>
			                  	:
			                  	<Box className="dd-t-list-time t-FCddfontblue-60"><span>{this.state.num}楼</span></Box>
			                }
						</HBox>
						<Box>
					  		<div className="t-LH1_6 t-omit t-FCddfontblue-40" style={{ width: "100%" }}>
								{createdDate}
							</div>

						</Box>
				  	</VBox>
				</HBox>
				<div className="t-FS14 t-LH1_3 t-omit2 t-MT6 t-MB12" style={{ width: "100%" }} dangerouslySetInnerHTML={{__html: this.state.content}}>
				</div>
			  	{photo_html}
			</div>
			<div className="t-BCf7 t-H10"></div>
		  	<div className="t-BCf">
	            <Item urlPrev={this.state.urlPrev} token={token} boardIsDelete={this.state.boardIsDelete} boardStatus={this.state.boardStatus} authorFloor={this.state.authorFloor} postId = {this.state.id} flushDataView={this.flushViewData.bind(this)} isAnonymityFloor={this.state.isAnonymity} />
	        </div>
		</div>
		);
	}
}